package com.hy.study.utils;

import java.util.Iterator;
import java.util.List;

public class IteratorTestForJdk18 {
    @FunctionalInterface
    public interface LoadFunc<T> {
        List<T> load(int start, int size);
    }

    public static class PageIterator<T> implements Iterator<T> {
        private int start = 0;
        private int size = 5;
        private int currentIndex;
        private boolean hasMore = true;
        private List<T> list;
        private LoadFunc<T> loadFunc;

        public PageIterator(LoadFunc<T> loadFunc) {
            this.loadFunc = loadFunc;
        }

        @Override
        public boolean hasNext() {
            if (list != null && list.size() > currentIndex) {
                return true;
            }
            // 当前的数据已经加载完毕，尝试加载下一批
            if (!hasMore) {
                return false;
            }
            list = loadFunc.load(start, size);
            if (list == null || list.isEmpty()) {
            // 没有加载到数据，结束
                return false;
            }
            if (list.size() < size) {
                // 返回条数小于限制条数，表示还有更多的数据可以加载
                hasMore = false;
            }
            currentIndex = 0;
            start += list.size();
            return true;
        }

        @Override
        public T next() {
            return list.get(currentIndex++);
        }
    }
}